package com.webwork.mood.system.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.webwork.mood.system.dataobject.User;
import com.webwork.mood.system.service.UserService;
import com.webwork.mood.util.DateFormat;
import com.webwork.mood.util.RSA;
import com.webwork.mood.util.StrManager;

@Controller
@SessionAttributes({ "verifyCode", "user" })
public class LoginController {

	@Autowired
	private UserService userSve;

	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public String login(
			@RequestParam("userId") String userId,
			@RequestParam("password") String password,
			@RequestParam("verifyCode") String vCode,
			@ModelAttribute("verifyCode") String genVCode,
			ModelMap modelMap) {
		if (!vCode.toLowerCase().equals(genVCode.toLowerCase())) {
			modelMap.put("tip", "验证码错误");
			return "index";
		}
		if (StrManager.isEmpty(userId) || StrManager.isEmpty(password)) {
			modelMap.put("tip", "帐号或者密码不能为空");
			return "index";
		}
		User queryObj = new User();
		queryObj.setUserId(userId);
		queryObj.setPassword(RSA.encodeBase(password));
		List<User> users = userSve.query(queryObj);
		if (users != null && users.size() == 1) {
			modelMap.put("user", users.get(0));
			System.out.println(users.get(0).getUserName() + "于" + DateFormat.Simple.format(new Date()) + "登入系统");
			return "main";
		} else {
			modelMap.put("tip", "帐号或者密码错误");
			return "index";
		}
	}

	@RequestMapping(value = "/logout")
	@ResponseBody
	public String logout(HttpServletRequest request, SessionStatus sessionStatus) {
		User user = (User) request.getSession().getAttribute("user");
		System.out.println(user.getUserName() + "于" + DateFormat.Simple.format(new Date()) + "退出系统");
		request.getSession().removeAttribute("user");
		request.getSession().removeAttribute("verifyCode");
		sessionStatus.setComplete();
		try {
			request.logout();
		} catch (ServletException e) {
			e.printStackTrace();
			return "fail";
		}
		return "success";
	}

}
